<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 搜索 -->
      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="账号" prop="username">
              <el-input
                v-model="queryParams.username"
                placeholder="请输入账号"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
                @clear="handleQuery"
              />
            </el-form-item>
            <el-form-item label="项目" prop="project">
              <el-input
                v-model="queryParams.project"
                placeholder="请输入项目"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
                @clear="handleQuery"
              />
            </el-form-item>
            <el-form-item label="联系方式" prop="phone">
              <el-input
                v-model="queryParams.phone"
                placeholder="请输入联系方式"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
                @clear="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="handleResetQuery">
                <i-ep-refresh />
                重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button type="success" @click="openDialog('ap2-form')"
                  ><i-ep-plus />新增</el-button
                >
                <el-button
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                  ><i-ep-delete />删除</el-button
                >
              </div>
            </div>
          </template>
          <!-- 列表 -->
          <el-table
            v-loading="loading"
            :data="pageData"
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              width="50"
              align="center"
              :resizable="false"
            />
            <el-table-column key="id" label="ID" align="center" width="60">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column
              label="项目"
              align="center"
              prop="project"
              :resizable="false"
            />
            <el-table-column label="标识" align="center" prop="project" />
            <el-table-column
              label="注释"
              align="center"
              prop="remark"
              :resizable="false"
            />
            <el-table-column
              label="内容"
              align="center"
              prop="account"
              :resizable="false"
            />
            <el-table-column
              label="用户状态"
              align="center"
              prop="statu"
              :resizable="false"
            >
              <template #default="{ row }">
                <el-tag v-if="row.statu === 1" type="primary" effect="dark">
                  正常
                </el-tag>
                <el-tag v-if="row.statu === 2" type="danger" effect="dark">
                  故障
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column
              label="联系方式"
              align="center"
              prop="phone"
              width="120"
              :resizable="false"
            />
            <el-table-column
              label="姓名"
              align="center"
              prop="username"
              :resizable="false"
            />
            <el-table-column
              label="创建时间"
              align="center"
              prop="CreatedTime"
              width="160"
              :resizable="false"
            />
            <el-table-column
              label="操作"
              fixed="right"
              align="center"
              width="150"
              :resizable="false"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('ap2-form', scope.row)"
                  ><i-ep-edit />编辑</el-button
                >
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                  ><i-ep-delete />删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.page"
            v-model:limit="queryParams.pagesize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
        v-if="dialog.type === 'ap2-form'"
        ref="ap2FormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="账号" prop="project">
          <el-input
            v-model="formData.project"
            :readonly="!!formData.id"
            placeholder="请输入账号"
          />
        </el-form-item>
        <el-form-item label="claid" prop="claid">
          <el-input v-model="formData.claid" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="姓名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="标注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="数据" prop="account">
          <el-input v-model="formData.account" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="状态:">
          <el-select v-model="formData.statu" clearable placeholder="请选择">
            <el-option
              v-for="item in statuOptions"
              :key="item.id"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input
            v-model="formData.phone"
            placeholder="请输入手机号码"
            maxlength="11"
          />
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Number2", // 这个name 是组件的名字，和路由中配置的 name 需要一致，路由跳转有两种形式，一种 通过 path跳转，一种通过 name 跳转，所以组件需要取名
  inheritAttrs: false,
});

const statuOptions = reactive([
  { id: 1, label: "正常", value: 1 },
  { id: 2, label: "故障", value: 2 },
]);

import Ap2API from "@/api/number2";

import { Ap2Form, Ap2PageVO, Ap2Query } from "@/api/number2/model";
import type { UploadInstance } from "element-plus";
import { genFileId } from "element-plus";

const queryFormRef = ref(ElForm); // 查询表单
const ap2FormRef = ref(ElForm); // 用户表单
// const uploadRef = ref<UploadInstance>(); // 上传组件

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<Ap2Query>({
  page: 1,
  pagesize: 10,
});
const dateTimeRange = ref("");
const total = ref(0); // 数据总数
const pageData = ref<Ap2PageVO[]>(); // 用户分页数据
// const deptList = ref<OptionType[]>(); // 部门下拉数据源
// const roleList = ref<OptionType[]>(); // 角色下拉数据源

// watch(dateTimeRange, (newVal) => {
//   if (newVal) {
//     queryParams.startTime = newVal[0];
//     queryParams.endTime = newVal[1];
//   }
// });

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "ap2-form",
  width: 800,
  title: "",
});

// 用户表单数据
const formData = reactive<Ap2Form>({
  status: 1,
});

// 用户导入数据
const importData = reactive({
  deptId: undefined,
  file: undefined,
  fileList: [],
});

// 校验规则
const rules = reactive({
  project: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  username: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  phone: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  Ap2API.getPage(queryParams)
    .then((data) => {
      pageData.value = data.data.data;
      total.value = data.data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  dateTimeRange.value = "";
  queryParams.page = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：ap2-form | 用户导入：user-import
 * @param id 用户ID
 */
async function openDialog(type: string, row?: { id: any }) {
  dialog.visible = true;
  dialog.type = type;

  if (dialog.type === "ap2-form") {
    // 用户表单弹窗
    if (row?.id) {
      dialog.title = "修改";
      Object.assign(formData, { ...row });
    } else {
      dialog.title = "新增";
    }
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：ap2-form | 用户导入：user-import
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type === "ap2-form") {
    ap2FormRef.value.resetFields();
    ap2FormRef.value.clearValidate();
    formData.id = undefined;
  } else if (dialog.type === "ap2-import") {
    importData.file = undefined;
    importData.fileList = [];
  }
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  if (dialog.type === "ap2-form") {
    ap2FormRef.value.validate((valid: any) => {
      if (valid) {
        const userId = formData.id;
        loading.value = true;
        if (userId) {
          Ap2API.update(userId, formData)
            .then(() => {
              ElMessage.success("修改成功");
              closeDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
        } else {
          Ap2API.add(formData)
            .then(() => {
              ElMessage.success("新增成功");
              closeDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
        }
      }
    });
  }
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const userIds = [id || removeIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    Ap2API.deleteByIds(userIds).then(() => {
      ElMessage.success("删除成功");
      handleResetQuery();
    });
  });
}

onMounted(() => {
  handleQuery();
});
</script>
